package com.wuyi.service.impl;

import com.wuyi.mapper.UserMapper;
import com.wuyi.pojo.User;
import com.wuyi.pojo.bo.RegisterBO;
import com.wuyi.service.UsersService;
import com.zc.enums.Sex;
import com.zc.utils.MD5Utils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

/**
 * @author 曾川
 * @version 1.0.0
 * @ClassName UsersServiceImpl.java
 * @Description 用户登录注册实现类
 * @createTime 2021年09月15日 15:04:00
 */
@Service
public class UsersServiceImpl implements UsersService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private Sid sid;

    private static final String USER_FACE = "wuyi-resource/files/zc/post/f6ce23c3-281c-45cb-b3a6-d30d8912fe29.png";



    @Transactional( propagation = Propagation.SUPPORTS)
    @Override
    public boolean queryUsernameIsExist(String userName) {

        Example userExample = new Example(User.class);
        Example.Criteria userCriteria = userExample.createCriteria();

        userCriteria.andEqualTo("userName",userName);

        User result = userMapper.selectOneByExample(userExample);


        return result == null ? false: true;
    }

    /**
     * 注册用户
     *
     * @param registerBO,
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public User createUser(RegisterBO registerBO) {

        String userId = sid.nextShort2();
        User user = new User();
        user.setUserId(userId);
        user.setUserName(registerBO.getUserName());
        //使用MD5加密
        try {
            user.setUserPassword(MD5Utils.getMD5Str(registerBO.getUserPassword()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //默认头像
        user.setUserFace(USER_FACE);
        user.setUserSex(Sex.SECRET.type);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());

        userMapper.insert(user);
        return user;
    }

    /**
     * 检索用户名和密码是否匹配，用于登录
     *
     * @param userName
     * @param userPassword
     * @return
     */
    @Transactional( propagation = Propagation.SUPPORTS)
    @Override
    public User queryUserForLogin(String userName, String userPassword) {

        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();


        criteria.andEqualTo("userName", userName);
        criteria.andEqualTo("userPassword", userPassword);

        User result = userMapper.selectOneByExample(example);

        return result;
    }


}
